use axum::{Router, Json};
use axum::extract::Query;
use axum::routing::get;
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use lazy_static::lazy_static;
use std::sync::Mutex;
use crate::models::{AttachedUser, Guide, Help, HelpAnswer, User};
use crate::utils::rds;
// use tower_cookies::Cookies;

// use crate::models::User;
// use crate::utils::cookie;

type RouterResult<T> = Result<T,String>;

// struct CachedUsers {
//     users: static mut HashMap<i32,String>
// }
// static mut USERS: HashMap<i32,String> = HashMap::new();
lazy_static!{
    static ref USERS: Mutex<HashMap<i32, String>> = Mutex::new(HashMap::new());
}

fn add_to_USERS(id:i32,name:String) {
    USERS.lock().unwrap().insert(id,name);
}

fn get_from_USERS(id:i32) -> Option<String> {
    if let Some(res) = USERS.lock().unwrap().get(&id){
        return Some(res.clone());
    }
    None
}


#[derive(Serialize,Deserialize)]
struct DataResponse<T>{
    pub status: &'static str,
    pub data: Vec<T>,
}

impl<T> DataResponse<T> {
    pub fn new(status:&'static str,data: Vec<T>) -> DataResponse<T> {
        DataResponse{
            status: status,
            data: data
        }
    }
}

pub fn router() -> Router {
    Router::new()
        .route("/", get(index))
        .route("/get_all", get(get_all))
        .route("/get_all_user", get(get_all_user))
        .route("/get_username_by_id",get(get_user_name_by_id))
        .route("/get_user_by_id",get(get_user_by_id))
        .route("/get_user_portrait",get(get_user_image_by_id))
        .route("/get_answers",get(get_help_answers_by_help_id))
        .route("/suspend_user",get(suspend_user))
        .route("/forbid_user",get(forbid_user))
        .route("/active_user",get(active_user))
}

async fn index() -> RouterResult<String> {
    Ok("欢迎来到交流页面！".to_string())
}

#[derive(Deserialize,Serialize,Debug)]
struct ChangeUserStatus{
    user_id:i32
}

async fn suspend_user(Query(query):Query<ChangeUserStatus>) -> Json<bool> {
    if let Ok(_) = User::suspend_user_by_id(query.user_id).await{
        return Json(true)
    }
    Json(false)
}

async fn forbid_user(Query(query):Query<ChangeUserStatus>) -> Json<bool> {
    if let Ok(_) = User::forbid_user_by_id(query.user_id).await{
        return Json(true)
    }
    Json(false)
}
async fn active_user(Query(query):Query<ChangeUserStatus>) -> Json<bool> {
    if let Ok(_) = User::active_user_by_id(query.user_id).await{
        return Json(true)
    }
    Json(false)
}

async fn get_all_user() -> Json<Vec<User>> {
    // let guides = Help::fe

    let users = User::fetch_all().await.unwrap();

    // let rs = DataResponse::new("ok",helps);

    Json(users)

}

async fn get_all() -> Json<Vec<Help>> {
    // let guides = Help::fe

    let helps = Help::fetch_all().await.unwrap();


    // let rs = DataResponse::new("ok",helps);

    Json(helps)

}

#[derive(Serialize,Deserialize,Debug)]
struct GetUserName{
    pub id: i32
}


// #[derive(Serialize,Deserialize,Debug)]
// struct SimpleUser{
//     pub id:i32,
//     pub name:String,
// }

/// 根据用户id返回用户名
async fn get_user_name_by_id(Query(query):Query<GetUserName>) -> Json<String> {

    if let Some(res) = get_from_USERS(query.id){
        let nickname = res;
        return Json(nickname);
    }else{
        if let Ok(user) = User::fetch_one_by_id(query.id).await{
            add_to_USERS(query.id,user.nickname.clone());
            return Json(user.nickname);
        }
    }

    Json("Wrong".to_string())


}

/// 根据用户id返回用户
async fn get_user_by_id(Query(query):Query<GetUserName>) -> Json<AttachedUser> {

    let user = User::fetch_one_by_id(query.id).await.unwrap();
    let image = user.get_user_image().await.unwrap();
    let attach_user = AttachedUser{
        id:user.id,
        nickname:user.nickname,
        image
    };

    Json(attach_user)


}

#[derive(Serialize,Deserialize)]
struct GetUserImage{
    pub user_id:i32
}

/// 获取一个用户的头像
async fn get_user_image_by_id(Query(query):Query<GetUserImage>) -> Json<String> {
    let user = User::fetch_one_by_id(query.user_id).await.unwrap();
    let url = user.get_user_image().await.unwrap();
    Json(url)
}

#[derive(Serialize,Deserialize)]
struct GetHelpAnswerByHelpId{
    pub help_id:i32
}

/// 获取某一求助贴的全部答案
async fn get_help_answers_by_help_id(Query(query):Query<GetHelpAnswerByHelpId>) -> Json<Vec<HelpAnswer>> {
    // let help = Help::fetch_one_by_id(query.help_id).await.unwrap();

    let answers = HelpAnswer::fetch_all_by_help_id(query.help_id).await.unwrap();
    Json(answers)
}